import { NextFunction, Request, Response } from "express";
import { LoginOpt } from "../../modules/login/types";
import { getUserInfo, trimStr, vertifyField } from "../../utils/common";
import { error } from "../../utils/resp";
import commentUser from "../services/user";
class UserMidd {
  /**
   * 校验字段
   * @param req
   * @param res
   * @param next
   */
  vertifyFields(req: Request, res: Response, next: NextFunction) {
    // 1. 获取用户名和密码
    let { username = "", password = "" } = req.body as LoginOpt;

    // 去掉左右空格
    username = trimStr(username);
    password = trimStr(password);
    // 2. 验证字段
    if (!vertifyField(username, password)) {
      error(res, { msg: "用户名或密码不能为空" });
    } else {
      // 校验通过
      next();
    }
  }

  /**
   * 判断是不是学生
   * @param req
   * @param _res
   * @param next
   */
  isStu = async (req: Request, _res: Response, next: NextFunction) => {
    const { id } = getUserInfo(req);

    const { role } = (await commentUser.getUserRole(id))[0]

    if (role !== "stu") {
      return next({ code: 200, msg: "该用户不是学生" });
    }
    // 处理下一个中间件
    next();
  };

  /**
   * 判断是不是老师
   * @param req
   * @param _res
   * @param next
   */
  isTch = async (req: Request, _res: Response, next: NextFunction) => {
    const { id } = getUserInfo(req);

    const { role } = (await commentUser.getUserRole(id))[0];

    if (role !== "tch") {
      return next({ code: 200, msg: "该用户不是教师" });
    }
    // 处理下一个中间件
    next();
  };
}

export default new UserMidd();
